package cn.hpclub.server.controller.admin;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.*;
import java.util.List;
import java.util.Arrays;
import java.util.concurrent.ConcurrentHashMap;

import cn.hpclub.server.model.*;
import cn.hpclub.server.util.Utils;
import cn.hpclub.server.util.excel.ExcelLogs;
import cn.hpclub.server.util.excel.ExcelUtil;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.render.JsonRender;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.poifs.filesystem.OfficeXmlFileException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Duang;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

import cn.hpclub.server.constant.Constant;
import cn.hpclub.server.service.BusinessAuthConfigService;
import cn.hpclub.server.service.TariffClassService;
import cn.hpclub.server.service.TariffService;
import cn.hpclub.server.util.InterfaceUtil;

/**
 * @FileName: BusinessAuthConfigController * @Author zhl
 * @Description:渠道类型与业务功能模组多级授权后台管理Controller
 * @Date 2016年6月27日 下午2:38:57
 * @CopyRight ZTE Corporation
 */
public class BusinessAuthConfigController extends BaseAdminController<BusinessAuthConfig>{
    private static final Logger logger                         = LoggerFactory
            .getLogger(BusinessAuthConfigController.class);
    private static final String URL_TEMPLATE  = "/template/admin/file/分级授权人员导入模版-大掌柜.xls";
    public static final int     UI_PAGER_NUMBER_DEFAULT        = 1;                   // UI默认起始页
    public static final int     UI_PAGER_SIZE_DEFAULT          = 10;                  // UI页容量
    public static final String  KEY_OPERATION                  = "operation";         // 当前是新增配置还是编辑配置
    public static final String  KEY_TYPE                       = "type";              // 当前操作的是哪个
    public static final String  LIST_SELECT_TYPE                       = "list_select_type";              // 当前权限列表是哪个业务类型下拉选项
    public static final String  KEY_FLOW_ID                    = "flowId";
    public static final String  KEY_IDS                        = "ids";
    public static final String  KEY_BUSINESS                   = "config_business";   // 操作的大类
    public static final String  KEY_BUSINESS_ID                = "config_business_id";// 具体的哪个
    public static final String  KEY_CREATOR_ORG_ID             = "creator_org_id";
    public static final int     SCHOOL_BUSINESS_SYS_CODE_START = 1000;                // 校园业务基础数据小类配置的值始于1000

    /**
     * 
     * @Title: list
     * @Description:分页获取首页弹窗数据列表
     */
    public void list(){
        initType();
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();
        if(!searchInfo.containsKey("org_id") || "-1".equals(searchInfo.get("org_id"))){
            searchInfo.put("org_id", InterfaceUtil.getOrgId() + "");
        }
        if(!searchInfo.containsKey(LIST_SELECT_TYPE)){
            searchInfo.put(LIST_SELECT_TYPE,getPara(LIST_SELECT_TYPE,"0"));
        }
        setAttrs(searchInfo);
        int org_id = Integer.parseInt(searchInfo.get("org_id"));
        setAttr("curr_org_id", org_id);
        String sqlExceptSelect = "";

        int businessType = Integer.parseInt(searchInfo.get(LIST_SELECT_TYPE));
        if(businessType < SCHOOL_BUSINESS_SYS_CODE_START){
            //资费类
            sqlExceptSelect = BusinessAuthConfigService.service.getSqlExceptSelect(searchInfo);
        } else{
            //非资费类，如选号入网，营销活动选号入网
//            sqlExceptSelect = BusinessAuthConfigService.service.getSqlExceptSelectForBroadband(searchInfo);
            sqlExceptSelect = BusinessAuthConfigService.service.getSqlExceptSelectForOtherBusiness(searchInfo,businessType);

        }
        findByPageForSearch(BusinessAuthConfigService.service.getSqlSelect(), sqlExceptSelect);
        render("/admin/business_auth_config_list.tpl");
    }

    private void initType(){
        List<Record> list = BusinessAuthConfigService.service.getBusinessTypeList();
        setAttr("businessTypeList", list);
    }

    /**
     * 新增权限配置初始化
     */
    public void addBusinessAuthConfig(){
        int type = getParaToInt(KEY_TYPE, BusinessAuthConfigService.TYPE_CITY);// 默认tab展示地市
        setAttr(KEY_TYPE, type);

        String operation = getPara(KEY_OPERATION, BusinessAuthConfigService.OPERATION_ADD);
        setAttr(KEY_OPERATION, operation);
        String flowId = getPara(KEY_FLOW_ID);
        if(BusinessAuthConfigService.OPERATION_ADD.equalsIgnoreCase(operation)){
            if(StrKit.isBlank(flowId)){
                // 1.空表示从新增配置按钮过来，生成流水号
                flowId = BusinessAuthConfigService.service.createFlowId();
            }
            // 说明不是第一次刷新，保存现有的flowId
            setAttr(KEY_FLOW_ID, flowId);
        }

        int pageSize = getParaToInt(PAGE_SIZE, UI_PAGER_SIZE_DEFAULT);
        int city_page_number = getParaToInt("city_page_number", UI_PAGER_NUMBER_DEFAULT);
        int store_page_number = getParaToInt("store_page_number", UI_PAGER_NUMBER_DEFAULT);
        int member_page_number = getParaToInt("member_page_number", UI_PAGER_NUMBER_DEFAULT);
        int channel_class_page_number = getParaToInt("channel_class_page_number", UI_PAGER_NUMBER_DEFAULT);
        int channel_cluster_page_number = getParaToInt("channel_cluster_page_number", UI_PAGER_NUMBER_DEFAULT);
        int channel_type_page_number = getParaToInt("channel_type_page_number", UI_PAGER_NUMBER_DEFAULT);
        ConcurrentHashMap<String, String> map = getSearchInfo();

        setAttr("cityPager",
                BusinessAuthConfigService.service.queryChannelCityTemp(city_page_number, pageSize, map, flowId));
        setAttr("storePager",
                BusinessAuthConfigService.service.queryChannelStoreTemp(store_page_number, pageSize, map, flowId));
        setAttr("memberPager",
                BusinessAuthConfigService.service.queryChannelMemberTemp(member_page_number, pageSize, map, flowId));
        setAttr("classPager", BusinessAuthConfigService.service.queryChannelClassTemp(channel_class_page_number,
                                                                                      pageSize, map, flowId));
        setAttr("clusterPager", BusinessAuthConfigService.service.queryChannelClusterTemp(channel_cluster_page_number,
                                                                                          pageSize, map, flowId));
        setAttr("typePager", BusinessAuthConfigService.service.queryChannelTypeTemp(channel_type_page_number, pageSize,
                                                                                    map, flowId));
        render("/admin/business_auth_config_input.tpl");
    }

    /**
     * 获取渠道类数据展示对话框
     */
    public void dialogChannel(){
        channel();
        render("/admin/business_auth_config_dialog_channel.tpl");
    }
    /**
     * 获取渠道类数据展示对话框
     */
    public void dialogChannelType(){
        channel();
        //获取所有地市列表
        List<Organization> cityList= Organization.dao.getOrganizationCityList(InterfaceUtil.getOrgId());
        setAttr("cityList",cityList);
        render("/admin/business_auth_config_dialog_channel_type.tpl");
    }
    private void channel() {
        int pageNumber = getParaToInt(PAGE_NUMBER, 1);
        int pageSize = getParaToInt(PAGE_SIZE, 10);
        ConcurrentHashMap<String, String> map = getSearchInfo();
        int type = getParaToInt(KEY_TYPE);// 根据这个查询是渠道大类，渠道簇还是渠道小类type-3即是对应的层级
        setAttr(KEY_TYPE, type);
        String operation = getPara(KEY_OPERATION);
        setAttr(KEY_OPERATION, operation);
        String flowId = getPara(KEY_FLOW_ID);
        setAttr(KEY_FLOW_ID, flowId);
        Page<Record> page = BusinessAuthConfigService.service.getChannel(type, pageNumber, pageSize, map);
        setAttr(Constant.Ui.PAGER, page);
    }

    /**
     * 获取人员数据展示对话框
     */
    public void dialogMember(){
        int pageNumber = getParaToInt(Constant.Ui.PAGER_NUMBER, 1);
        int pageSize = getParaToInt(Constant.Ui.PAGER_SIZE, 10);
        String operation = getPara(KEY_OPERATION);
        setAttr(KEY_OPERATION, operation);
        String flowId = getPara(KEY_FLOW_ID);
        setAttr(KEY_FLOW_ID, flowId);
        ConcurrentHashMap<String, String> map = getSearchInfo();
        setAttr(Constant.Ui.PAGER, BusinessAuthConfigService.service.getMember(pageNumber, pageSize, map));
        render("/admin/business_auth_config_dialog_member.tpl");
    }

    /**
     * 获取门店数据展示对话框
     */
    public void dialogStore(){
        int pageNumber = getParaToInt(Constant.Ui.PAGER_NUMBER, 1);
        int pageSize = getParaToInt(Constant.Ui.PAGER_SIZE, 10);
        String operation = getPara(KEY_OPERATION);
        setAttr(KEY_OPERATION, operation);
        String flowId = getPara(KEY_FLOW_ID);
        setAttr(KEY_FLOW_ID, flowId);
        ConcurrentHashMap<String, String> map = getSearchInfo();
        setAttr(Constant.Ui.PAGER, BusinessAuthConfigService.service.getStore(pageNumber, pageSize, map));
        render("/admin/business_auth_config_dialog_store.tpl");
    }

    /**
     * 获取门店数据展示对话框
     */
    public void dialogCity(){
        int pageNumber = getParaToInt(Constant.Ui.PAGER_NUMBER, 1);
        int pageSize = getParaToInt(Constant.Ui.PAGER_SIZE, 10);

        String operation = getPara(KEY_OPERATION);
        setAttr(KEY_OPERATION, operation);
        String flowId = getPara(KEY_FLOW_ID);
        setAttr(KEY_FLOW_ID, flowId);

        int configBusinessId = getParaToInt(KEY_BUSINESS_ID, 0);
        int creatorOrgId = getParaToInt(KEY_CREATOR_ORG_ID, 0);
        setAttr(KEY_BUSINESS_ID, configBusinessId);
        setAttr(KEY_CREATOR_ORG_ID, creatorOrgId);

        ConcurrentHashMap<String, String> map = getSearchInfo();

        setAttr(Constant.Ui.PAGER, BusinessAuthConfigService.service.getCity(pageNumber, pageSize, map, operation,
                                                                             configBusinessId, creatorOrgId, flowId));
        render("/admin/business_auth_config_dialog_city.tpl");
    }

    /**
     * 新增，按照地市、门店、人员、渠道大类、渠道簇、渠道小类配置
     */
    public void addAuthOrizationByType(){
        String flowId = getPara(KEY_FLOW_ID);
        int type = getParaToInt(KEY_TYPE);
        String operation = getPara(KEY_OPERATION);
        Integer[] ids = Utils.string2Int(getPara(KEY_IDS), "#");
        boolean ret = false;
        String city_org_ids = getPara("city_org_ids",null);
        Integer[] citys = removeFirstIf(city_org_ids,-1);//去掉全选项

        if(BusinessAuthConfigService.OPERATION_ADD.equalsIgnoreCase(operation)){// 新增的新增
            ret = BusinessAuthConfigService.service.saveByTypeTemp(flowId, type, ids,citys);
        } else if(BusinessAuthConfigService.OPERATION_EDIT.equalsIgnoreCase(operation)){// 编辑的新增
            int business = getParaToInt(KEY_BUSINESS);
            int businessId = getParaToInt(KEY_BUSINESS_ID);
            int creatorOrgId = getParaToInt(KEY_CREATOR_ORG_ID, 0);
            ret = BusinessAuthConfigService.service.saveByType(type, ids, business, businessId, creatorOrgId,citys);
        }
        if(ret){
            ajaxJsonSuccessMessage("OK");
        } else{
            ajaxJsonErrorMessage("FAIL");
        }
    }

    /**
     *
     * @param city_org_ids
     * @param removed 如果第一项是全选项，就去掉，-1就传-1,0就传0
     * @return
     */
    private Integer[] removeFirstIf(String city_org_ids,int removed) {
        Integer[] citysTmp = Utils.string2Int(city_org_ids,",");
        Integer [] citys;
        if(citysTmp.length>0 && citysTmp[0] == removed){//去掉全选项
            citys = new Integer[citysTmp.length-1];
            for (int i = 0 ; i < citysTmp.length-1; i ++) {
                citys[i] = citysTmp[i+1];
            }
        }else {
            citys = citysTmp;
        }
        return citys;
    }

    /**
     * 修改权限配置初始化
     */
    public void editBusinessAuthConfig(){

        int config_business_id = getParaToInt(KEY_BUSINESS_ID, 0);
        int config_business = getParaToInt(KEY_BUSINESS, 0);
        int creator_org_id = getParaToInt(KEY_CREATOR_ORG_ID, 0);
        setAttr(KEY_BUSINESS_ID, config_business_id);
        setAttr(KEY_CREATOR_ORG_ID, creator_org_id);
        setAttr(KEY_BUSINESS, config_business);
        int type = getParaToInt(KEY_TYPE, BusinessAuthConfigService.TYPE_CITY);// 默认tab展示地市
        setAttr(KEY_TYPE, type);
        int pageSize = getParaToInt(PAGE_SIZE, 10);
        setAttr(KEY_OPERATION, BusinessAuthConfigService.OPERATION_EDIT);
        setAttr(KEY_FLOW_ID, "");
        ConcurrentHashMap<String, String> map = getSearchInfo();
        setAttr("cityPager",
                BusinessAuthConfigService.service.getCityPagerForRegular(getParaToInt("city_page_number", 1), pageSize,
                                                                         config_business_id, creator_org_id, map));
        setAttr("storePager",
                BusinessAuthConfigService.service.getStorePagerForRegular(getParaToInt("store_page_number", 1),
                                                                          pageSize, config_business_id, creator_org_id,
                                                                          map));
        setAttr("memberPager",
                BusinessAuthConfigService.service.getMemberPagerForRegular(getParaToInt("member_page_number", 1),
                                                                           pageSize, config_business_id, creator_org_id,
                                                                           map));
        setAttr("classPager",
                BusinessAuthConfigService.service
                        .getChannelClassPagerForRegular(getParaToInt("channel_class_page_number", 1), pageSize,
                                                        config_business_id, creator_org_id, map));
        setAttr("clusterPager",
                BusinessAuthConfigService.service
                        .getChannelClusterPagerForRegular(getParaToInt("channel_cluster_page_number", 1), pageSize,
                                                          config_business_id, creator_org_id, map));
        setAttr("typePager",
                BusinessAuthConfigService.service
                        .getChannelTypePagerForRegular(getParaToInt("channel_type_page_number", 1), pageSize,
                                                       config_business_id, creator_org_id, map));
        render("/admin/business_auth_config_input.tpl");
    }

    /*
     * 跳转到数据业务配置页面
     */
    public void toBusinessAuthConfigData(){
        setAttr(KEY_FLOW_ID, getPara(KEY_FLOW_ID, ""));
        initType();
        render("/admin/business_auth_config_data.tpl");
    }

    public void saveConfigData(){
        int business = getParaToInt(KEY_BUSINESS);
        Integer[] ids = getParaValuesToInt(KEY_IDS);
        String flowId = getPara(KEY_FLOW_ID);
        logger.info("business=" + business + ",flowId=" + flowId + ",ids=" + Arrays.toString(ids));
        BusinessAuthConfigService service = Duang.duang(BusinessAuthConfigService.class, Tx.class);
        boolean result = false;
        try{
            result = service.saveConfig(business, flowId, ids);
        }
        catch(Exception e){
            e.printStackTrace();
        }
        if(result){
            ajaxJsonSuccessMessage("OK");
        } else{
            ajaxJsonErrorMessage("FAIL");
        }
    }

    /**
     * 统一的删除方法,通过operation区分，由于设计的原因，新增的删除的id是实体类的id，编辑的删除id是关系表的id
     */
    public void deleteAuthorization(){
        Integer[] ids = Utils.string2Int(getPara(KEY_IDS), "#");
        String operation = getPara(KEY_OPERATION);
        int type = getParaToInt(KEY_TYPE);
        setAttr(KEY_OPERATION, operation);
        setAttr(KEY_TYPE, type);
        boolean ret = false;
        if(BusinessAuthConfigService.OPERATION_ADD.equalsIgnoreCase(operation)){// 新增的删除
            String flowId = getPara(KEY_FLOW_ID);
            ret = BusinessAuthConfigService.service.deleteByTypeTemp(type, flowId, ids);
        } else if(BusinessAuthConfigService.OPERATION_EDIT.equalsIgnoreCase(operation)){// 编辑的删除
            ret = BusinessAuthConfigService.service.deleteByType(ids);
        }
        if(ret){
            ajaxJsonSuccessMessage("OK");
        } else{
            ajaxJsonErrorMessage("FAIL");
        }
    }

    /**
     * 已配置权限列表中删除一条权限配置数据
     */
    public void deleteBusinessAuthConfig(){
        String[] ids = getParaValues("ids");
        if(ids == null || ids.length <= 0){
            ajaxJsonErrorMessage("删除失败，无选中项");
        }
        int delCount = 0;
        for(String id : ids){
            if(id.contains("#%#")){
                String[] idArr = id.split("#%#");
                int config_business_id = Integer.parseInt(idArr[0]);
                int creator_org_id = Integer.parseInt(idArr[1]);
                int resultDelete = new BusinessAuthConfigService().service.deleteBusinessAuthConfig(config_business_id,
                                                                                                    creator_org_id);
                if(resultDelete > 0)
                    delCount++;
            }
        }
        String message = "";
        int code = 1005;
        if(delCount == ids.length){
            message = "删除成功";
            code = 1000;
        } else if(delCount > 0 && delCount < ids.length){
            message = "部分数据删除失败";
            code = 1000;
        } else{
            message = "删除失败";
        }
        JSONObject json = new JSONObject();
        json.put("resultCode", code);
        json.put("message", message);
        renderJson(json);
    }

    /**
     * 人员导入模板下载
     */
    public void template(){
        renderFile(URL_TEMPLATE);
    }
    /**
     * 获取业务配置类型数据（基础数据大类小类配置）
     * 
     * @Title: loadBusiness
     * @Description:TODO void
     */
    public void loadBusiness(){
        JSONArray busDatas = new JSONArray();
        String actType = getPara("actType", "");
        logger.info("actType = " + actType);
        if(StrKit.isBlank(actType)){
            logger.error("-----actType isBlank-----");
            renderJson(busDatas);
            return;
        }
        // 根据类型值判断从哪个表取数据（1000以下属于资费类数据，否则属于非资费类数据）
        if(actType.length() < 4){
            // 活动类型值长度小于4位表示是资费类业务，通过类型值取资费大类（业务类型）和资费小类（业务数据）
            busDatas = getTariffDatas(actType);
            // logger.info("busDatas :" + busDatas.toString());
        } else{
            // 活动类型值长度大于4位（1000开始）表示是其他业务，如通用的宽带预约套餐、终端销售名称等，需要分别进行判断并在相应表取数据
//            if(Constant.BUSINESS_CONFIG_TYPE_BROADBAND.equals(actType)){
//                busDatas = BroadbandService.service.getBroadbandByActType();
//            }
            int businessType = Integer.parseInt(actType);
            // 活动类型值长度大于4位（1000开始）表示是其他业务，如通用的宽带预约套餐、终端销售名称等，需要分别进行判断并在相应表取数据
            busDatas = BusinessAuthConfigService.service.getBusinessToAuth4GeneralMember(businessType);
        }
        renderJson(busDatas);
    }

    /**
     * @Title: getTariffDatas
     * @Description:TODO
     * @param actType
     * @return JSONArray
     */
    private JSONArray getTariffDatas(String actType){
        List<Record> tariffClassList = TariffClassService.service.getTariffClassByActType(actType);
        JSONArray busDatas = TariffService.service.getTariffByTariffClass(tariffClassList);

        return busDatas;
    }

    private String getString(String fullString){
        if(StringUtils.isBlank(fullString) || "null".equalsIgnoreCase(fullString)){
            return "";
        }
        return fullString;
    }

    /**
     * 人员导入
     */
    public void upload(){
        String result = null;
        int status = 1;
        try{
            result = importMemberData();
        }
        catch(OfficeXmlFileException | EncryptedDocumentException | InvalidFormatException e){
            e.printStackTrace();
            result = "格式错误，请上传excel 2003/2007格式文件";
            status = 0;
        }
        catch(Exception e){
            e.printStackTrace();
            result = "导入数据失败,请联系管理员!";
            status = 0;
        }
        finally{
            Map<String, Object> jsonMap = new HashMap<String, Object>();
            jsonMap.put("status", status);
            jsonMap.put("result", result);
            render(new JsonRender(jsonMap).forIE());
        }
    }
    private String importMemberData()
            throws FileNotFoundException, EncryptedDocumentException, InvalidFormatException{
        int successCount = 0;
        String errorMsg = "";
        InputStream inputStream = new FileInputStream(getFile().getFile());
        ExcelLogs logs = new ExcelLogs();
        Collection<Map> importExcel = ExcelUtil.importExcel(Map.class, inputStream, "yyyy/MM/dd HH:mm:ss", logs, 0);
        String operation = getPara(KEY_OPERATION);
        setAttr(KEY_OPERATION,operation);
        int type = getParaToInt(KEY_TYPE);
        setAttr(KEY_TYPE,type);
        int configBusinessId = getParaToInt("config_business_id",0);
        setAttr("config_business_id",configBusinessId);
        int configBusiness = getParaToInt("config_business",0);
        setAttr("config_business",configBusiness);
        int creatorOrgId = getParaToInt("creator_org_id",InterfaceUtil.getAdminId());
        setAttr("creator_org_id",creatorOrgId);
        String flowId = getPara(KEY_FLOW_ID);
        setAttr(KEY_FLOW_ID,flowId);
        int i = 1;

        int loginOrgId = getParaToInt("org_id",InterfaceUtil.getOrgId());
        Map<Integer,Integer> orgIdMap = InterfaceUtil.getOrganizationReturnIntegerMap(loginOrgId);

        for(Map<?, ?> m : importExcel){
            String prefix = "\r\n第" + i + "条：";
            i++;
            if(!validImportExcelCellData(m)){
                errorMsg += prefix + "姓名、工号、手机号不能为空！";
                continue;
            }
            String name = getString(ExcelUtil.removeSpace(String.valueOf(m.get("姓名"))));
            String empCode = getString(ExcelUtil.removeSpace(String.valueOf(m.get("工号"))));
            String phoneNumber = getString(ExcelUtil.removeSpace(String.valueOf(m.get("手机号"))));
            MemberOrg member = MemberOrg.dao.getMemberOrgbyUserNameAndEmpCodeAndName(phoneNumber,empCode,name);
            int orgMemberId = member.getInt(MemberOrg.ORG_ID);
            if(member == null){
                errorMsg += prefix + "手机号" + phoneNumber + "，工号"+empCode+" 对应人员信息在大掌柜后台不存在";
                continue;
            }
            if(3 == member.getInt(MemberOrg.MEMBER_TYPE)){
                errorMsg += prefix + "手机号" + phoneNumber + "，工号"+empCode+" 对应人员是泛店员，不允许授权";
                continue;
            }
            if(!orgIdMap.containsKey(orgMemberId)){
                errorMsg += prefix + "手机号" + phoneNumber + "，工号"+empCode+" 对应人员你无权限操作";
                continue;
            }

            int memberOrgId = member.getInt(MemberOrg.ID);
            if("add".equalsIgnoreCase(operation)){
                //查询数据是否已存在，存在就直接跳过
                String selectExistData = "select * from "+Constant.Table.TABLE_BUSINESS_AUTH_CONFIG_TEMP+" WHERE " +
                        "flow_id=? AND config_type=?" +
                        " AND config_type_id=? ";
                Record record = Db.findFirst(selectExistData,flowId,3,memberOrgId);
                if(record!=null && record.getInt("id")>0){
                    errorMsg += prefix + " 该员工已授权，无需重复授权";
                    continue;
                }
                BusinessAuthConfigTemp bt = new BusinessAuthConfigTemp();
                bt.set(BusinessAuthConfigTemp.FLOW_ID,flowId);
                bt.set(BusinessAuthConfigTemp.CONFIG_TYPE,3);//3代表人员授权
                bt.set(BusinessAuthConfigTemp.CONFIG_TYPE_ID,memberOrgId);
                if(!bt.save()){
                    errorMsg += prefix + "保存到数据库时发生错误";
                    continue;
                }
            } else if("edit".equalsIgnoreCase(operation)){
                //查询数据是否已存在，存在就直接跳过
                String selectExistData = "select * from "+Constant.Table.TABLE_BUSINESS_AUTH_CONFIG+" WHERE config_type=? AND config_type_id=?" +
                        " AND config_business=? AND config_business_id=? AND creator_org_id=? ";
                Record record = Db.findFirst(selectExistData,3,memberOrgId,configBusiness,configBusinessId,creatorOrgId);
                if(record!=null && record.getInt("id")>0){
                    errorMsg += prefix + " 该员工已授权，无需重复授权";
                    continue;
                }
                BusinessAuthConfig b = new BusinessAuthConfig();
                b.set(BusinessAuthConfig.CONFIG_TYPE,3);//3代表人员授权
                b.set(BusinessAuthConfig.CONFIG_TYPE_ID,memberOrgId);
                b.set(BusinessAuthConfig.CONFIG_BUSINESS,configBusiness);
                b.set(BusinessAuthConfig.CONFIG_BUSINESS_ID,configBusinessId);
                b.set(BusinessAuthConfig.CREATOR_ORG_ID,creatorOrgId);
                b.set(BusinessAuthConfig.UPDATED_TIME,new Date());
                if(!b.save()){
                    errorMsg += prefix + "保存到数据库时发生错误";
                    continue;
                }
            }
            successCount++;
        }
        int failedCount = importExcel.size() - successCount;
        if((failedCount > 0) && (errorMsg.length() > 200)){
            errorMsg = errorMsg.substring(0, 200) + "\r\n。。。。。。";
        }
        return "成功：" + successCount + "条," + "失败：" + failedCount + "条。" + (failedCount > 0 ? errorMsg : "");
    }
    private boolean validImportExcelCellData(Map<?, ?> data){
        String name = String.valueOf(data.get("姓名"));
        String empCode = String.valueOf(data.get("工号"));
        String phoneNumber = String.valueOf(data.get("手机号"));
        if(StringUtils.isBlank(name) || "null".equalsIgnoreCase(name) || StringUtils.isBlank(empCode)
                || "null".equalsIgnoreCase(empCode)|| StringUtils.isBlank(phoneNumber)
                || "null".equalsIgnoreCase(phoneNumber)){
            logger.error("validImportExcelCellData data error");
            return false;
        }
        return true;
    }


    /**
     * 一键删除当前配置中所有人员信息
     */
    public void deleteAllMemberAuthCfg(){
        String operation = getPara(KEY_OPERATION);
        int type = getParaToInt(KEY_TYPE);
        setAttr(KEY_OPERATION, operation);
        setAttr(KEY_TYPE, type);

        int deleteResult=0;
        if(BusinessAuthConfigService.OPERATION_ADD.equalsIgnoreCase(operation)){
            String flowId = getPara(KEY_FLOW_ID);
            setAttr(KEY_FLOW_ID, flowId);
            deleteResult = BusinessAuthConfigService.service.deleteAllMemberForBusinessAuthConfigTemp(type,flowId);
        }else if(BusinessAuthConfigService.OPERATION_EDIT.equalsIgnoreCase(operation)){
            int configBusiness = getParaToInt(KEY_BUSINESS);
            int configBusinessId = getParaToInt(KEY_BUSINESS_ID);
            int creatorOrgId = getParaToInt(KEY_CREATOR_ORG_ID,InterfaceUtil.getOrgId());
            setAttr(KEY_BUSINESS,configBusiness);
            setAttr(KEY_BUSINESS_ID,configBusinessId);
            setAttr(KEY_CREATOR_ORG_ID,creatorOrgId);
            deleteResult = BusinessAuthConfigService.service.deleteAllMemberForBusinessAuthConfig(type,configBusiness,configBusinessId,creatorOrgId);
        }
        if(deleteResult > 0){
            ajaxJsonSuccessMessage("OK");
        } else{
            ajaxJsonErrorMessage("FAIL");
        }
    }

}
